# $Id: View.pm,v 1.2 2004/06/21 12:12:30 ibo Exp $
package CGI::FOGE2::View;

use strict;
use CGI::FOGE2::Tools;

our @ISA = qw();

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
       
    my %args = @_;
    my @mandatory_keys = ();
    my $self = {
	form => $args{form},
	view => undef,
    };
    bless ($self, $class);

    print STDERR "LOSHOOOOOOO\n\n" unless defined($args{form});

    $self->{view} = $self->parse_view();
    return $self;
}

sub setform {
    my $self = shift;
    my ($form) = @_;
    $self->{form} = $form;
}

sub parse_view {
    my $self = shift;
    my $form = $self->{form};
    my %tables = ();
    
    #return \%tables unless defined CGI::param('configview');
    
    foreach my $section (@{$form->{sections}}) {
	my $table = $section->get_table_name();
	print STDERR "\n\nADDING SECTION ", $table;
	next unless defined (CGI::param('showsec_' . $table));
	for my $question (@{$section->{questions}}) {
	    my $qname = ${$question->generate_field_names()}[0];
	    next unless defined (CGI::param('showq_' . $qname));
	    print STDERR 'VIEWWWWWW ADDINGGG: ' , $qname , "\n\n";
	    $tables{$table}->{$qname} = 1;
	}
    }

    return \%tables;
}

sub as_hidden {
    my $self = shift;
    my $view = $self->{view};

    my $ret = '';
    foreach my $sec (keys %$view) {
	$ret .= CGI::hidden('showsec_' . $sec, 'on');
	foreach my $q (keys %{$view->{$sec}}) {
	    $ret .= CGI::hidden('showq_' . $q, 'on');
	}
    }

    if ($ret) {
	$ret .= CGI::hidden(-name => 'configview', -value => 'on');
    }
    return $ret;
}

sub contains_section {
    my $self = shift;
    my $secname = shift;

    return defined($self->{view}->{$secname});
}

sub contains_question {
    my $self = shift;
    my $secname = shift;
    my $qname = shift;

    return defined($self->{view}->{$secname}->{$qname});
}

sub get_structure {
    my $self = shift;
    return $self->{view};
}

sub as_query_string {
    my $self = shift;
    my $view = $self->{view};
    
    my $ret = '';
    foreach my $sec (keys %$view) {
	$ret .= ";showsec_${sec}=on";
	foreach my $question (keys %{$view->{$sec}}) {
	    $ret .= ";showq_${question}=on"
	}
    }
    return $ret;
}

1;
